<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Cookie;
use think\Request;
use sendsms\SmsDemo;
use app\index\model\KnowUser;
use app\index\model\PhoneNum;
use app\common\service\SessionUser;



class Login extends Controller
{
	private $wx_appid = 'wx8f55d70da457e929';
	private $wx_appsecret = '3860b146c323eb30a684533d01c7591f';

	public function __construct(){
		parent::__construct();
		$this->assign('redirects','http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
		if(input('get.redirect')) $this->assign('redirects',input('get.redirect'));
	}


	public function login(){
		$user = unserialize(cookie('user'));
		if(!$user){
			if(input('post.')){
				$params = input('post.');
				if(empty($params['phone']) || empty($params['password']))
					die(alert('必填项不能为空'));
				$data = KnowUser::updateUserPass($params, 'pc', '');
				if($data){
					$redirect = '/';
					if($_GET['redirect'])  $redirect = $_GET['redirect'];
					$this->redirect($redirect);
				}else{
					die(alert('账号或密码不正确'));
				}
			}else{
				$url = $_SERVER['HTTP_REFERER'];
				$path = parse_url($url);
				return $this->fetch('',[
					'title' => '登录',
					'path' => $path['path'],
					'redirect' => $_GET['redirect'],
					'wechatUrl' => 'https://open.weixin.qq.com/connect/qrconnect?appid='. $this->wx_appid .'&redirect_uri='.urlencode('https://www.atxunda.com/third/wechat.html?redirect='.$_GET['redirect']).'&response_type=code&scope=snsapi_login&state=' . md5 ( uniqid ( rand (), true ) ) . '#wechat_redirect'
				]);
			}
		}else{
			if($_GET['redirect']) $this->redirect($_GET['redirect']);
			$this->redirect('/course/1');
		}
	}


	public function register(){
		$user = unserialize(cookie('user'));
		$salt = input('get.salt');
		if(!$salt) {
			$salt = cookie('salt');
		} else {
			Common::getSalt($salt);
		}
		if($user){
			if($_GET['redirect']) $this->redirect($_GET['redirect']);
			$this->redirect('/course/1');
		}
		if(input('post.')){
			if(empty(input('post.phone'))) die(alert('手机号不能为空'));
			if(!(preg_match('/^1[3456789]\d{9}$/', input('post.phone')))){
				$this->error('手机号格式不正确');die;
			}
			$data = KnowUser::insertUser(input('post.'));
			if($data['code'] == 400){
				die(alert('手机号已被注册，请您直接登录即可','/login?redirect='.$_GET['redirect']));
			}else if($data['code'] == 401){
				die(alert('账号格式不正确'));
			}else{
				$redirect = '/course/1';
				if($_GET['redirect'])  $redirect = $_GET['redirect'];
				$this->redirect($redirect);
			}
		}else{
			return $this->fetch('',[
				'title' => '注册',
				'redirect' => $_GET['redirect'],
			]);
		}
	}

	public function forget(){
		$user = unserialize(cookie('user'));
		if(!$user){
			if(input('post.')){
				$params = input('post.');
				if(empty($params['phone']) || empty($params['password']))
					die(alert('必填项不能为空'));
				if($params['password'] != $params['repassword'])
					die(alert('新密码跟确认密码不一致'));
				$data = KnowUser::changePass($params);
				if($data){
					$redirect = '/login.html?redirect='.$_GET['redirect'];
					$this->redirect($redirect);
				}else{
					die(alert('账户不存在'));
				}
			}else{
				$url = $_SERVER['HTTP_REFERER'];
				return $this->fetch('',[
					'title' => '忘记密码',
					'redirect' => $_GET['redirect'],
				]);
			}
		}else{
			if($_GET['redirect']) $this->redirect($_GET['redirect']);
			$this->redirect('/');
		}
	}



	public function complete(){
		$user = unserialize(cookie('user'));
		if($user){
			if($_GET['redirect']) $this->redirect($_GET['redirect']);
			$this->redirect('/');
		}
		if(input('post.')){
			$arr = input('post.');
			$openid = cookie('login_wechat');
			$nickname = Db::table('know_user_third')->where('openid',$openid)->value('nickname');
			$arr['nickname'] = $nickname;
			$arr['password'] = '123456';
			$data = KnowUser::insertUser($arr);
			if($data['code'] == 400){
				$data = KnowUser::updateUser($arr['phone']);
			}else if($data['code'] == 401){
				$this->error('账号格式不正确');
			}
			Db::table('know_user_third')->where('openid',$openid)->update(['user_id'=>$data['know_user_id']]);
			Cookie::delete('login_wechat');
			$redirect = '/';
			KnowUser::where(['know_user_id'=>$data['know_user_id']])->update(['know_nickname'=>$nickname]);
			if($_GET['redirect']) $redirect = $_GET['redirect'];
			$this->redirect($redirect);
		}else{
			return $this->fetch('',[
				'title' => '补全手机号',
				'redirect' => $_GET['redirect'],
			]);
		}
	}


		/**
	 * [getcode 获取验证码]
	 * @return [type] [description]
	 */
	public function getcode(Request $request){
		$param = $request->param();
		if($param['phone'] && preg_match('/^1[3456789]\d{9}$/', $param['phone'])){
			$instance = new SmsDemo();
			$num = rand_num();
			$phone_num = PhoneNum::getLastOne($param['phone']);
			if (!empty($phone_num) && (time() - strtotime($phone_num['time'])) < 180){
				$data['code'] = 400;
				$data['msg'] = '请不要频繁获取验证码';
			}else{
				$instance->sendSms($param['phone'],$num);
				$data['code'] = 200;
				PhoneNum::setPhone($param['phone'],$num);
			}
		}else{
			$data['code'] = 400;
			$data['msg'] = '手机号不合法';
		}
		return json($data);
	}


	/**
	 * [checkcode 验证验证码]
	 * @return [type] [description]
	 */
	public function checkcode(Request $request){
		$param = $request->param();
		$phone_num = PhoneNum::getLastOne($param['phone']);
		// (time() - strtotime($phone_num['time'])) < 180 &&
		if(!empty($phone_num) &&  $param['code'] == $phone_num['num']){
			$data['code'] = 200;
		}else{
			$data['code'] = 400;
			$data['msg'] = '验证码错误';
		}
		return json($data);
	}


	/**
	 * [getphone 验证手机号是否被注册]
	 * @return [type] [description]
	 */
	public function checkphone(Request $request){
		$param = $request->param();
		$user = KnowUser::getDataOne('know_phone|know_email',$param['phone']);
		$data['code'] = 400;
		if ( $param['btn'] == 'reg'){
			if ( !$user ){
				$data['code'] = 200;
			}else{
				$data['msg'] = '账户被注册';
			}
		} else if ($param['btn'] == 'com'){
			$data['code'] = 200;
		} else {
			if ( $user ){
				$data['code'] = 200;
			}else{
				$data['msg'] = '账户不正确';
			}
		}
		return json($data);
	}

	public function logout(Request $request){
		$param = $request->param();
		SessionUser::logout();
		$url = $param['redirect'] ?: $_SERVER['HTTP_REFERER'];
		$this->redirect($url);
	}

	public function testaaacvb(){
		$request = Request::instance();
		$phone = $request->param('phone');
		$data = KnowUser::getDataOne('know_phone|know_email',$phone);
		if($data){
			$arr = array(
				'login_time'=>date('Y-m-d H:i:s',time()),
				'login_ip'=>$_SERVER['REMOTE_ADDR'],
				'login_num'=>$data['login_num']+1
			);
			if(empty($data['token'])) $arr['token'] = $data['token'] = getLoginToken();
			KnowUser::where(['know_user_id'=>$data['know_user_id']])->update($arr);
			$arr = array(
				'id' => $data['know_user_id'],
				'phone' => $data['know_phone']
			);
			Cookie::set('user',serialize($arr),3600*24*30);
			Cookie::set('token',$data['token'],3600*24*30);
			$this->redirect('/');
		}else{
			$this->redirect('/login');
		}
	}

}